package com.woniu.serverdriveruser.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.internalcommon.constant.CommonStatusEnum;
import com.woniu.internalcommon.constant.DriverCarConstants;
import com.woniu.internalcommon.dto.*;
import com.woniu.internalcommon.response.DriverUserExistsResponse;
import com.woniu.internalcommon.response.OrderDriverResponse;
import com.woniu.serverdriveruser.mapper.CarMapper;
import com.woniu.serverdriveruser.mapper.DriverCarBindingMapper;
import com.woniu.serverdriveruser.mapper.DriverMapper;
import com.woniu.serverdriveruser.mapper.DriverUserWorkStatusMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DriverService {
    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private DriverUserWorkStatusMapper driverUserWorkStatusMapper;

    @Autowired
    private DriverCarBindingMapper driverCarBindingMapper;

    @Autowired
    private CarMapper carMapper;
    @Autowired
    private DriverCarBindingService driverCarBindingService;

    /**
     * 新增司机
     * @param driver
     */
    public void add(DriverUser driver){
        LocalDateTime now = LocalDateTime.now();
        driver.setGmtCreate(now);
        driver.setGmtModified(now);

        driverMapper.insert(driver);
        // 初始化 司机工作状态表
        DriverUserWorkStatus driverUserWorkStatus = new DriverUserWorkStatus();
        driverUserWorkStatus.setDriverId(driver.getId());
        driverUserWorkStatus.setWorkStatus(0);
        driverUserWorkStatus.setGmtModified(now);
        driverUserWorkStatus.setGmtCreate(now);
        driverUserWorkStatusMapper.insert(driverUserWorkStatus);
    }

    /**
     * 根据电话查询司机（司机状态有效：1）
     * @param driverPhone
     * @return
     */
    public ResponseResult<DriverUserExistsResponse> getDriverByPhone(String driverPhone){
        Map<String,Object> map = new HashMap<>();
        map.put("driver_phone", driverPhone);
        map.put("state", DriverCarConstants.DRIVER_STATE_VALID);
        List<DriverUser> driverUsers = driverMapper.selectByMap(map);
        // 当前电话号码查到状态为1(有效)的司机，集合为空，返回失败
        if (driverUsers.isEmpty()){
            return ResponseResult.fail(CommonStatusEnum.DRIVER_NOT_EXITST.getCode(),CommonStatusEnum.DRIVER_NOT_EXITST.getValue());
        }
        DriverUser driverUser = driverUsers.get(0);
        DriverUserExistsResponse driverUserExistsResponse = new DriverUserExistsResponse();
        driverUserExistsResponse.setIfExists(1);
        driverUserExistsResponse.setDriverPhone(driverPhone);
        return ResponseResult.success(driverUserExistsResponse);
    }

    /**
     * 查询可用司机信息 用于订单司机信息生成
     */
    public ResponseResult<OrderDriverResponse> getAvailableDriver(Long carId) {
        //车辆和司机绑定关系查询
        QueryWrapper<DriverCarBindingRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("car_id", carId);
        queryWrapper.eq("bind_state", DriverCarConstants.DRIVER_CAR_BIND);
        DriverCarBindingRelationship driverCarBindingRelationship = driverCarBindingMapper.selectOne(queryWrapper);
        Long driverId = driverCarBindingRelationship.getDriverId();

        // 司机工作状态查询
        QueryWrapper<DriverUserWorkStatus> newQueryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driver_id", driverId);
        queryWrapper.eq("work_status", DriverCarConstants.DRIVER_WORK_STATUS_START);
        DriverUserWorkStatus driverUserWorkStatus = driverUserWorkStatusMapper.selectOne(newQueryWrapper);
        if (driverUserWorkStatus == null){
            return ResponseResult.fail(CommonStatusEnum.AVAILABLE_DRIVER_EMPTY.getCode(),CommonStatusEnum.AVAILABLE_DRIVER_EMPTY.getValue());
        }else{
            //司机工作状态有效：为1，再查司机具体信息
            QueryWrapper<DriverUser> secQueryWrapper = new QueryWrapper<>();
            secQueryWrapper.eq("id", driverId);
            DriverUser driverUser = driverMapper.selectOne(secQueryWrapper);
            //查询车辆信息
            QueryWrapper<Car> carQueryWrapper = new QueryWrapper<>();
            carQueryWrapper.eq("id", carId);
            Car car = carMapper.selectOne(carQueryWrapper);

            //根据司机和汽车信息  生成订单司机消息
            OrderDriverResponse orderDriverResponse = new OrderDriverResponse();
            orderDriverResponse.setCarId(carId);
            orderDriverResponse.setDriverId(driverId);
            orderDriverResponse.setDriverPhone(driverUser.getDriverPhone());
            orderDriverResponse.setLicenseId(driverUser.getLicenseId());
            orderDriverResponse.setVehicleNo(car.getVehicleNo());
            orderDriverResponse.setVehicleType(car.getVehicleType());

            return ResponseResult.success(orderDriverResponse);
        }


    }

    /**
     * 根据id删除司机
     * @param id
     */
    /**
     * 根据id删除司机
     * @param id
     */
    public void deleteById(Long id) {
        //解绑前，先查  绑定关系
        QueryWrapper<DriverCarBindingRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driver_id",id);
        DriverCarBindingRelationship relationship = driverCarBindingMapper.selectOne(queryWrapper);
        //如果有绑定，先解除
        if (relationship != null){
            driverCarBindingService.unBinding(relationship);
        }
        //再修改司机工作状态
        QueryWrapper<DriverUserWorkStatus> statusQueryWrapper = new QueryWrapper<>();
        statusQueryWrapper.eq("driver_id",id);
        DriverUserWorkStatus workStatus = driverUserWorkStatusMapper.selectOne(statusQueryWrapper);
        workStatus.setWorkStatus(DriverCarConstants.DRIVER_WORK_STATUS_STOP);
        driverUserWorkStatusMapper.updateById(workStatus);

        driverMapper.deleteById(id);
    }

    /**
     * 修改司机信息
     * @param driver
     */
    public ResponseResult update(DriverUser driver) {
        driver.setGmtModified(LocalDateTime.now());
        driverMapper.updateById(driver);
        return ResponseResult.success("修改成功");
    }

    /**
     * 多条件——动态SQL——查询司机
     * @param apiBossDriver
     * @return
     */
    public ResponseResult<Page<DriverUser>> findDriver(ApiBossDriver apiBossDriver) {
        QueryWrapper<DriverUser> driverUserQueryWrapper = new QueryWrapper<>();
        Page<DriverUser> objectPage = new Page<>();
        objectPage.setCurrent(apiBossDriver.getPageNum());
        objectPage.setSize(apiBossDriver.getPageSize());
        DriverUser driverUser = apiBossDriver.getDriverUser();
        if (driverUser!=null) {
            if (driverUser.getAddress() != null && !driverUser.getAddress().isEmpty()) {
                driverUserQueryWrapper.like("address", driverUser.getAddress());
            } else if (driverUser.getDriverName() != null && !driverUser.getDriverName().isEmpty()) {
                driverUserQueryWrapper.like("driver_name", driverUser.getDriverName());
            } else if (driverUser.getDriverPhone() != null && !driverUser.getDriverPhone().isEmpty()) {
                driverUserQueryWrapper.like("driver_phone", driverUser.getDriverPhone());
            } else if (driverUser.getDriverGender() != null) {
                driverUserQueryWrapper.eq("driver_gender", driverUser.getDriverGender());
            }
            Page<DriverUser>selectPage = driverMapper.selectPage(objectPage, driverUserQueryWrapper);
            return ResponseResult.success(selectPage);
        }
        Page<DriverUser>selectPage = driverMapper.selectPage(objectPage,null);
        return ResponseResult.success(selectPage);
    }

    public ResponseResult<Page<DriverUser>> getAll(Integer current, Integer size) {
        Page<DriverUser> page = new Page<>(current,size);
        Page<DriverUser> driverUserPage = driverMapper.selectPage(page, null);
        return ResponseResult.success(driverUserPage);
    }

    /**
     * 根据手机号查询司机信息(查具体信息)
     * @param driverPhone
     * @return
     */
    public ResponseResult<DriverUser> getDriverUserByPhone(String driverPhone) {
        QueryWrapper<DriverUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driver_phone",driverPhone);
        DriverUser driverUser = driverMapper.selectOne(queryWrapper);
        return ResponseResult.success(driverUser);
    }
}
